using UnityEngine;
using Delta2DGame.Base;

namespace Delta2DGame.State
{
    /// <summary>
    /// 敌人返回原位状态
    /// </summary>
    public class ReturnState : EnemyState
    {
        [SerializeField] private float moveSpeed = 2.5f;
        [SerializeField] private float returnThreshold = 0.5f;
        [SerializeField] private float attackRange = 3f;

        private Vector3 originalPosition;

        public ReturnState(EnemyStateMachine stateMachine, EnemyController enemy, string animBoolName)
            : base(stateMachine, enemy, animBoolName)
        {
            originalPosition = enemy.transform.position;
        }

        public override void Enter()
        {
            base.Enter();
            // 记录初始位置（确保每次进入状态时更新）
            originalPosition = enemy.GetComponent<EnemyPatrolPoints>().originalPosition;
        }

        public override void Update()
        {
            base.Update();

            // 检测玩家是否在攻击范围内
            if (IsPlayerInAttackRange())
            {
                stateMachine.SwitchState(stateMachine.attackState);
                return;
            }

            // 到达初始位置后切换回巡逻状态
            if (Vector2.Distance(enemy.transform.position, originalPosition) <= returnThreshold)
            {
                stateMachine.SwitchState(stateMachine.patrolState);
                return;
            }
        }

        public override void FixedUpdate()
        {
            base.FixedUpdate();
            // 移动到初始位置
            enemy.transform.position = Vector2.MoveTowards(
                enemy.transform.position,
                originalPosition,
                moveSpeed * Time.fixedDeltaTime
            );
        }

        private bool IsPlayerInAttackRange()
        {
            GameObject player = GameObject.FindGameObjectWithTag("Player");
            if (player != null)
            {
                float distance = Vector2.Distance(enemy.transform.position, player.transform.position);
                return distance <= attackRange;
            }
            return false;
        }
    }
}